package lu.med.praxiswahl.wahlumed.client.utilities;

import java.io.File;
import java.util.Hashtable;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 
 * @author Lars Holger Roth
 */
public class PrintConfiguration {
	// Die Klasse speichert in einem Hash die Werte für die
	// Koordinaten von Elementen zum Drucken. Die Werte werden
	// aus einer Konfigurationsdatei gelesen
	private Hashtable<String, Integer> coords = new Hashtable<String, Integer>();

	public PrintConfiguration(String configFile, String tag) {

		File file = new File(configFile);
		XMLReader reader = XMLReader.getPrintConfigXMLReaderInstance(file);

		Node tagNode = reader.getDoc().getElementsByTagName(tag).item(0);

		this.fillOutCoordsArray(tagNode);
	}

	private void fillOutCoordsArray(Node tagNode) {
		NodeList tagChilds = tagNode.getChildNodes();
		coords.clear();
		
		for (int i = 0; i < tagChilds.getLength(); i++) {
			Node node = tagChilds.item(i);

			if (node.getNodeType() != Node.ELEMENT_NODE) {
				if (!node.getNodeValue().trim().isEmpty()) {
					coords.put(tagNode.getNodeName(), new Integer(Integer.parseInt(node.getNodeValue()
							.trim())));
				}

			} else if (node.getNodeType() == Node.ELEMENT_NODE) {
				this.fillOutCoordsArray(node);
			}

		}
		//System.out.println("coord size::"+coords.size());
	}

	public PrintConfiguration(String fileName) {

		File file = new File(fileName);
		XMLReader reader = XMLReader.getInputConfigXMLReaderInstance(file);
		Node rootNode = reader.getDoc().getFirstChild();

		NodeList rootChilds = rootNode.getChildNodes();

		coords.clear();
		
		for (int i = 0; i < rootChilds.getLength(); i++) {
			Node node = rootChilds.item(i);

			if (node.getNodeType() == Node.ELEMENT_NODE) {
				coords.put(
						node.getNodeName(),
						new Integer(Integer.parseInt(node.getChildNodes()
								.item(0).getNodeValue())));
			}

		}
	}

	public int getCoordsFor(String key) {
		int ret = 0;
		try {
			ret = coords.get(key);
		} catch (NullPointerException e) {
			System.out
					.println("PrintConfiguration::getCoordsFor::Key fehlerhaft::"
							+ key);
		}
		return ret;
	}
}
